package com.itlong.cloud.padbot.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.itlong.cloud.POJO.DTO.app.AppPadBotRobotDTO;
import com.itlong.cloud.POJO.DTO.property.PropertyPadBotDeliveryTaskDTO;
import com.itlong.cloud.POJO.PO.PadBotRobotDeliveryTaskRecordPO;
import com.itlong.cloud.POJO.PO.PadBotRobotMapInfoPO;
import com.itlong.cloud.POJO.PO.PadBotRobotTargetInfoPO;
import com.itlong.cloud.POJO.VO.app.AppPadBotMapVO;
import com.itlong.cloud.POJO.VO.app.AppPadBotTargetPointVO;
import com.itlong.cloud.POJO.VO.app.RobotDeliveryTaskInfoVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.enumerate.DataStatusEnum;
import com.itlong.cloud.enumerate.PadBotErrorCodeEnum;
import com.itlong.cloud.padbot.dao.IPadBotRobotDao;
import com.itlong.cloud.padbot.service.IPadBotRobotService;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.data.handler.SqlUtil;
import com.itlong.cloud.utils.date.DateUtil;
import com.itlong.cloud.utils.encrypt.Md5EncryptUtil;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.random.LogicIdUtil;
import com.itlong.cloud.utils.words.NumberHandlerUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <desc>
 *      派宝机器人业务处理实现类
 * </desc>
 *
 * @createDate2021/1/6
 **/
@Service
public class PadBotRobotServiceImpl implements IPadBotRobotService {

    @Value("${" + PlatformConstants.PAD_BOT_ROBOT_APP_KEY + "}")
    public String PAD_BOT_ROBOT_APP_KEY = "7340aa05c6a94506b4355c7f85b8663a";

    @Value("${" +PlatformConstants.PAD_BOT_ROBOT_APP_TOKEN+ "}")
    public String PAD_BOT_ROBOT_APP_TOKEN = "eyyHpHaTPXKMVq3G";

    @Autowired
    private IPadBotRobotDao iPadBotRobotDao;
//    /**
//     * <desc>
//     *      获取目标点列表
//     * </desc>
//     *
//     * @param appPadBotRobotDTO 调用派宝接口参数DTO
//     * @return
//     * @Author Zhu.yj
//     * @createDate  2021/1/6
//     */
//    @Override
//    public List<AppPadBotTargetPointVO> getTargetPointList(AppPadBotRobotDTO appPadBotRobotDTO) throws Exception {
//        Map<String, String> params = new HashMap<>();
//        params.put("serialNumber", appPadBotRobotDTO.getSerialNumber());
//        String result = this.getRequestInfo(params, "http://s.padbot.cn:9080/cloud/openapimap/loadIndoorMapList.action");
//        JSONObject jsonObject = JSON.parseObject(result);
//        //返回成功
//        if (PadBotErrorCodeEnum.SUCCESS.getErrorCode().equals(jsonObject.getString("messageCode"))){
//            List<AppPadBotMapVO> mapVOList = JSONArray.parseArray(JSON.toJSONString(jsonObject.get("data")), AppPadBotMapVO.class);
//            //目前做一个演示版本，只做单楼层，不做跨楼层，即只有一张地图，且该地图暂时写死
//        }
//        return new ArrayList<>();
//    }


    /**
     * <desc>
     *      取消派送任务
     * </desc>
     *
     * @param appPadBotRobotDTO 调用派宝接口参数DTO
     * @return
     * @Author Zhu.yj
     * @createDate  2021/1/6
     */
    @Override
    public boolean cancelDeliveryTask(AppPadBotRobotDTO appPadBotRobotDTO) throws Exception {
        Map<String, String> params = new HashMap<>();
        params.put("serialNumber", "PW1090");
        params.put("taskId", appPadBotRobotDTO.getTaskId());
        String result = this.getRequestInfo(params, "http://s.padbot.cn:9080/cloud/openapidelivery/cancelDeliveryTask.action");
        JSONObject jsonObject = JSON.parseObject(result);
        return PadBotErrorCodeEnum.SUCCESS.getErrorCode().equals(jsonObject.getString("messageCode"));
    }

    /**
     * <desc>
     *      新建派送任务
     * </desc>
     *
     * @param appPadBotRobotDTO 调用派宝接口参数DTO
     * @return
     * @Author Zhu.yj
     * @createDate  2021/1/6
     */
    @Override
    public String createDeliveryTask(AppPadBotRobotDTO appPadBotRobotDTO) throws Exception {
        Map<String, String> params = new HashMap<>();
        Date nowTime = new Date();
        String orderNumber = LogicIdUtil.bussinessId();
        String pickPassword = NumberHandlerUtil.randomNum(6);
        params.put("serialNumber", "PW1090");
        params.put("orderNumber", orderNumber);
        params.put("loadingPointId", appPadBotRobotDTO.getLoadingPointId());
        params.put("targetPointId", appPadBotRobotDTO.getTargetPointId());
        params.put("phoneNumber", appPadBotRobotDTO.getPhoneNumber());
        params.put("pickPassword", pickPassword);
        String result = this.getRequestInfo(params, "http://s.padbot.cn:9080/cloud/openapidelivery/createDeliveryTask.action");
        JSONObject jsonObject = JSON.parseObject(result);
        RobotDeliveryTaskInfoVO taskInfoVO = JSON.parseObject(jsonObject.getString("data"), RobotDeliveryTaskInfoVO.class);
        //保存派送任务列表

        String deliveryGoods = "";
        //处理订单信息
        if (appPadBotRobotDTO.getGoodsInfoList() != null && !appPadBotRobotDTO.getGoodsInfoList().isEmpty()){
            StringBuilder goodsInfo = new StringBuilder();
            for (Map map : appPadBotRobotDTO.getGoodsInfoList()){
                goodsInfo.append(map.get("goodsName")).append("*").append(map.get("goodsAmount")).append(",");
            }
            deliveryGoods = goodsInfo.substring(0, goodsInfo.length() -1);
        }

        PadBotRobotDeliveryTaskRecordPO taskRecordPO = new PadBotRobotDeliveryTaskRecordPO();
        taskRecordPO.setTaskId(taskInfoVO.getTaskId());
        taskRecordPO.setProjectId(appPadBotRobotDTO.getProjectId());
        taskRecordPO.setLoadingPointId(appPadBotRobotDTO.getLoadingPointId());
        taskRecordPO.setTargetPointId(appPadBotRobotDTO.getTargetPointId());
        taskRecordPO.setPhoneNumber(appPadBotRobotDTO.getPhoneNumber());
        taskRecordPO.setOrderNumber(orderNumber);
        taskRecordPO.setPickPassword(pickPassword);
        taskRecordPO.setDeliveryGoods(deliveryGoods);
        taskRecordPO.setDeliveryStatus(Integer.parseInt(taskInfoVO.getDeliveryStatus()));
        taskRecordPO.setCreateUserId(appPadBotRobotDTO.getUserId());
        taskRecordPO.setOperateUserId(appPadBotRobotDTO.getUserId());
        taskRecordPO.setStatus(DataStatusEnum.NORMAL.getType());
        taskRecordPO.setCreateTime(nowTime);
        taskRecordPO.setUpdateTime(nowTime);
        iPadBotRobotDao.save(SqlUtil.durableData(taskRecordPO, PlatformConstants.TABLE_SAVE));
        return params.get("pickPassword");
    }

    /**
     * <desc>
     *      更新派宝机器人地图信息
     * </desc>
     *
     * @param  serialNumber 机器人序列号
     * @return
     * @Author Zhu.yj
     * @createDate  2021/1/8
     */
    @Override
    public Integer saveMapTargetInfo(String serialNumber) throws Exception {
        Map<String, String> params = new HashMap<>();
        params.put("serialNumber", serialNumber);
        String result = this.getRequestInfo(params, "http://s.padbot.cn:9080/cloud/openapimap/loadIndoorMapList.action");
        JSONObject jsonObject = JSON.parseObject(result);
        //返回成功
        if (PadBotErrorCodeEnum.SUCCESS.getErrorCode().equals(jsonObject.getString("messageCode"))){
            List<AppPadBotMapVO> mapVOList = JSONArray.parseArray(JSON.toJSONString(jsonObject.get("data")), AppPadBotMapVO.class);
            //删除原数据
            List<String> mapIdList = iPadBotRobotDao.getMapIdBySerialNumber(serialNumber);
            if (!mapIdList.isEmpty()){
                iPadBotRobotDao.deleteMapInfo(mapIdList);
                iPadBotRobotDao.deleteTargetInfo(mapIdList);
            }
            List<PadBotRobotMapInfoPO> padBotRobotMapInfoPOList = new ArrayList<>();
            List<PadBotRobotTargetInfoPO> padBotRobotTargetInfoPOList = new ArrayList<>();
            Date nowTime = new Date();
            //目前做一个演示版本，只做单楼层，不做跨楼层，即只有一张地图，且该地图暂时写死
            for (AppPadBotMapVO appPadBotMapVO : mapVOList){
                PadBotRobotMapInfoPO mapInfoPO = new PadBotRobotMapInfoPO();
                mapInfoPO.setMapId(appPadBotMapVO.getId());
                mapInfoPO.setRobotNumber(serialNumber);
                mapInfoPO.setMapName(appPadBotMapVO.getCustomMapName());
                mapInfoPO.setWidth(appPadBotMapVO.getWidth());
                mapInfoPO.setHeight(appPadBotMapVO.getHeight());
                mapInfoPO.setResolution(new BigDecimal(appPadBotMapVO.getResolution()));
                mapInfoPO.setFloor(appPadBotMapVO.getFloorStr());
                mapInfoPO.setImageUrl(appPadBotMapVO.getImageUrl());
                mapInfoPO.setMapIsDefault(appPadBotMapVO.getDefault());
                mapInfoPO.setStatus(DataStatusEnum.NORMAL.getType());
                mapInfoPO.setCreateTime(nowTime);
                mapInfoPO.setUpdateTime(nowTime);
                padBotRobotMapInfoPOList.add(mapInfoPO);
                for (AppPadBotTargetPointVO targetPointVO : appPadBotMapVO.getTargetPointList()){
                    PadBotRobotTargetInfoPO targetInfoPO = new PadBotRobotTargetInfoPO();
                    targetInfoPO.setTargetId(targetPointVO.getId());
                    targetInfoPO.setMapId(appPadBotMapVO.getId());
                    targetInfoPO.setTargetName(targetPointVO.getName());
                    targetInfoPO.setCoordinateX(targetPointVO.getCoordinateX());
                    targetInfoPO.setCoordinateY(targetPointVO.getCoordinateY());
                    targetInfoPO.setAngle(targetPointVO.getAngle());
                    targetInfoPO.setStayTime(targetPointVO.getStayTime());
                    targetInfoPO.setType(targetPointVO.getType());
                    targetInfoPO.setCallbackUrl(targetPointVO.getCallbackUrl());
                    targetInfoPO.setStatus(DataStatusEnum.NORMAL.getType());
                    targetInfoPO.setCreateTime(nowTime);
                    targetInfoPO.setUpdateTime(nowTime);
                    padBotRobotTargetInfoPOList.add(targetInfoPO);
                }
            }
            if (!padBotRobotMapInfoPOList.isEmpty()){
                iPadBotRobotDao.batchSavePadBotRobotMapList(padBotRobotMapInfoPOList);
            }
            if (!padBotRobotTargetInfoPOList.isEmpty()){
                iPadBotRobotDao.batchSavePadBotRobotTargetList(padBotRobotTargetInfoPOList);
            }
        }
        return 1;
    }

    /**
     * <desc>
     *      配置回调地址
     * </desc>
     *
     * @param
     * @return
     * @Author Zhu.yj
     * @createDate  2021/1/12
     */
    @Override
    public boolean configCallbackUrl(PropertyPadBotDeliveryTaskDTO deliveryTaskDTO) throws Exception {
        Map<String, String> params = new HashMap<>();
        params.put("serialNumber", deliveryTaskDTO.getSerialNumber());
        params.put("urlType", deliveryTaskDTO.getUrlType());
        params.put("url", deliveryTaskDTO.getUrl());
        String result = this.getRequestInfo(params, "http://s.padbot.cn:9080/cloud/openapiconfig/configCallbackUrl.action");
        JSONObject jsonObject = JSON.parseObject(result);
        return PadBotErrorCodeEnum.SUCCESS.getErrorCode().equals(jsonObject.getString("messageCode"));
    }

    /**
     * <desc>
     *      查询回调地址
     * </desc>
     *
     * @param deliveryTaskDTO 配送任务列表
     * @return
     * @Author Zhu.yj
     * @createDate  2021/1/12
     */
    @Override
    public String getCallbackUrl(PropertyPadBotDeliveryTaskDTO deliveryTaskDTO) throws Exception {
        Map<String, String> params = new HashMap<>();
        params.put("serialNumber", deliveryTaskDTO.getSerialNumber());
        params.put("urlType", deliveryTaskDTO.getUrlType());
        String result = this.getRequestInfo(params, "http://s.padbot.cn:9080/cloud/openapiconfig/queryCallbackUrl.action");
        JSONObject jsonObject = JSON.parseObject(result);
        if (jsonObject != null){
            return jsonObject.getString("url");
        }
        return "";
    }


    /**
     * <desc>
     *      获取请求响应字段
     * </desc>
     *
     * @param params 参数map
     * @return
     * @Author Zhu.yj
     * @createDate  2021/1/6
     */
    private String getRequestInfo(Map<String, String> params, String remoteUrl) throws Exception{
        JSONObject jsonObject = new JSONObject();
        Map<String, String> signMap = new HashMap<>();
        Map<String, String> systemMap = new HashMap<>();
        long timeStamp = System.currentTimeMillis() / 1000;
        for (Map.Entry<String, String> entry : params.entrySet()) {
            signMap.put(entry.getKey(), entry.getValue());
            jsonObject.put(entry.getKey(), entry.getValue());
        }
        systemMap.put("time", Long.toString(timeStamp));
        systemMap.put("language", "zh-CN");
        systemMap.put("sign", Md5EncryptUtil.getPadBotSign(signMap, timeStamp, PAD_BOT_ROBOT_APP_KEY, PAD_BOT_ROBOT_APP_TOKEN));
        systemMap.put("appkey", PAD_BOT_ROBOT_APP_KEY);
        jsonObject.put("system", systemMap);
        return HttpProtocolUtil.httpPost(remoteUrl, JSON.toJSONString(jsonObject));
    }



    public static void main(String[] args) {
        try {
            AppPadBotRobotDTO appPadBotRobotDTO = new AppPadBotRobotDTO();
            appPadBotRobotDTO.setSerialNumber("PW1090");
            PropertyPadBotDeliveryTaskDTO deliveryTaskDTO =new PropertyPadBotDeliveryTaskDTO();
//            deliveryTaskDTO.setSerialNumber("PW1090");
//            deliveryTaskDTO.setUrlType("1205");
//            deliveryTaskDTO.setUrl("http://tmp.foreign.jia-r.com/foreign/padbot/receiveDeliveryTask");
            appPadBotRobotDTO.setTaskId("2c928aa676f5b7dd0176ff660d5e2cc1");
            PadBotRobotServiceImpl appPadBotRobotService = new PadBotRobotServiceImpl();
//            appPadBotRobotService.configCallbackUrl(deliveryTaskDTO);
            appPadBotRobotService.cancelDeliveryTask(appPadBotRobotDTO);
            SimpleDateFormat dateFormat =new SimpleDateFormat(DateUtil.DATE_FORMAT_TYPE1);
            Date nowTime = new Date();
            String nowtime = dateFormat.format(nowTime);
            System.out.println(dateFormat.parse(nowtime).getTime());
        }catch (Exception e){
            throw new DataAccessException();
        }
    }




}
